package com.payment.common.wxutils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class WxSingleton {



    //缓存accessToken 的Map,map中包含 一个accessToken 和 缓存的时间戳
    private Map<String, String> map = new HashMap<String,String>();

    private WxSingleton() {

    }

    private static WxSingleton single = null;

    // 静态工厂方法
    public static WxSingleton getInstance() {
        if (single == null) {
            single = new WxSingleton();
        }
        return single;
    }

    public Map<String, String> getMap() {
        return map;
    }

    public void setMap(Map<String, String> map) {
        this.map = map;
    }

    public static WxSingleton getSingle() {
        return single;
    }

    public static void setSingle(WxSingleton single) {
        WxSingleton.single = single;
    }

    /**
     * 获取 accessToken Jsapi_ticket 已加入缓存机制
     * @param appid
     * @param appsecret
     * @return
     */
    public Map<String,Object> getAccessTokenAndJsapiTicket(String appid, String appsecret) {
        Map<String,Object> result = new HashMap<String,Object>();
        WxSingleton singleton = WxSingleton.getInstance();
        Map<String, String> map = singleton.getMap();
        String time = map.get("time");//从缓存中拿数据
        String accessToken = map.get("access_token");//从缓存中拿数据
        String jsapiticket = map.get("jsapiticket");//从缓存中拿数据
        Long nowDate = new Date().getTime();
        //这里设置过期时间 3000*1000就好了
        if (accessToken != null && time != null && nowDate - Long.parseLong(time) < 3000 * 1000) {
            System.out.println("-----从缓存读取access_token："+accessToken);
            System.out.println("-----从缓存读取jsapiticket："+jsapiticket);
            //从缓存中拿数据为返回结果赋值
            result.put("access_token", accessToken);
            result.put("jsapiticket", jsapiticket);
        } else {
            //获取accessToken
            accessToken = MobileUtil.getAccessToken(appid, appsecret);
            if (null != accessToken){
                String ticket = MobileUtil.getTicket(accessToken);
                map.put("access_token", accessToken);
                map.put("jsapiticket", ticket);
                //将信息放置缓存中
                map.put("time", nowDate + "");

                //为返回结果赋值
                result.put("access_token", accessToken);
                result.put("jsapiticket", ticket);
            }
        }
        return result;
    }
}
